package assignments.sagarjoshi.springtms;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;


public class AllocationListFragment extends Fragment implements AdapterView.OnItemClickListener
{
    public AllocationListFragment() {/* Required empty public constructor*/ }



    public interface OnAllocationInteractionListener
    {

        public void onAllocationChanged(int data);
        public void setCounts(int count1, int count2, int count3, int count4);
    }

    private OnAllocationInteractionListener mListener;
    ListView list;
    AllocationItemClass[] data;
    int total_count,alloc_count,reject_count,course_id;
    SQLiteDatabase readDB,writeDB;


    @Override
    public void onAttach(Activity activity)
    {
        super.onAttach(activity);
        try
        {
            mListener = (OnAllocationInteractionListener) activity;
        } catch (ClassCastException e)
        {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState)
    {
       View v=inflater.inflate(R.layout.fragment_allocation_list, container, false);
        list=(ListView)v.findViewById(R.id.allocationlist);
        list.setOnItemClickListener(this);
        String table=MyDatabaseHelper.DATABASE_TABLE_TRAINEE;
        String[] projection={MyDatabaseHelper.KEY_ID,MyDatabaseHelper.KEY_TRAINEE_ID,
                                                   MyDatabaseHelper.KEY_TRAINEE_NAME};

        String order=MyDatabaseHelper.KEY_TRAINEE_ID;

        readDB = new MyDatabaseHelper(getActivity()).getReadableDatabase();
        Cursor traineeCursor=readDB.query(table,projection,null,null,null,null,order);
        total_count=traineeCursor.getCount();

        if(total_count==0)
        {
            Toast.makeText(getActivity(),"No data found",Toast.LENGTH_SHORT).show();
            return v;
        }
        ((TextView)getActivity().findViewById(R.id.val_count1)).setText(String.valueOf(total_count));
        data = new AllocationItemClass[total_count];

        for(int i=0;i<total_count;i++)
        {
            traineeCursor.moveToPosition(i);
            data[i]=new AllocationItemClass();
            data[i].item_id=traineeCursor.getInt(0);
            data[i].Trainee_id=traineeCursor.getString(1);
            data[i].Trainee_name=traineeCursor.getString(2);
            data[i].status="";
        }

        setAllocationData();
        //setList();

        return v;
    }


     private void setList()
     {
          AllocationAdapter adapter = new AllocationAdapter(getActivity(),data);
          list.setAdapter(adapter);

         reject_count=alloc_count=0;
         for(int i=0;i<total_count;i++)
         {
                if(!data[i].status.isEmpty())

                 alloc_count++;

             if(data[i].status.equals("rejected"))
             {
                 reject_count++;
             }


         }
         mListener.setCounts(total_count,alloc_count,reject_count,total_count-alloc_count);

     }

    private void setAllocationData()
    {
         course_id=getActivity().getIntent().getIntExtra("item_id",0);
         if(course_id==0) return;
         String table=MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
         String[] columns= new String[]{MyDatabaseHelper.KEY_ID, MyDatabaseHelper.KEY_TRAINEE_ID,
                                            MyDatabaseHelper.KEY_ALLOCATED_DATE,MyDatabaseHelper.KEY_STATUS, MyDatabaseHelper.KEY_COMMENTS};

         String clause=MyDatabaseHelper.KEY_COURSE_ID+"=?";
         String[] args= new String[]{String.valueOf(course_id)};
         String order = MyDatabaseHelper.KEY_TRAINEE_ID;
        Cursor innerCursor=readDB.query(table,columns,clause,args,null,null,order);
         if(innerCursor==null)
         {
             Log.i("message from setallocationdata = ","cursor is null");
             return;
         }
         alloc_count=innerCursor.getCount();
         /*if(alloc_count==0)
         {
             return;
         }*/
         for(int i=0;i<alloc_count;i++)
         {
             innerCursor.moveToPosition(i);
             for(int j=0;j<data.length;j++)
             {
                 if(data[j].item_id==innerCursor.getInt(1))
                 {
                     data[j].allocation_date=innerCursor.getString(2);
                     data[j].status=innerCursor.getString(3);
                     data[j].comments=innerCursor.getString(4);
                     break;
                 }
             }
         }
        setList();

    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {

       if(data[position].status.equals("allocated") || data[position].status.equals("confirmed") || data[position].status.equals("rejected"))
       {
           data[position].status="";
           data[position].allocation_date=getString(R.string.unvailable);

       }
        else
       {
           data[position].status="allocated";

           String[] elements = ((Button)getActivity().findViewById(R.id.lbl_coursedate)).getText().toString().split("/");
           data[position].allocation_date=elements[2]+"-"+elements[1]+"-"+elements[0];
       }

        data[position].comments="";
        setList();
    }



    @Override
    public void onDetach()
    {
        super.onDetach();
        mListener = null;
    }

    public void onSave()
    {


        writeDB=new MyDatabaseHelper(getActivity()).getWritableDatabase();
        String table = MyDatabaseHelper.DATABASE_TABLE_TRAINEE_COURSE;
        String clause=MyDatabaseHelper.KEY_COURSE_ID+"=? and "+MyDatabaseHelper.KEY_TRAINEE_ID+"=?";

        for(int i=0;i<data.length;i++)
        {
            String[] args = new String[]{String.valueOf(course_id),String.valueOf(data[i].item_id)};



            if(data[i].status.isEmpty())
            {

                int result=writeDB.delete(table,clause,args);

            }

            else
            {
                Cursor c = readDB.query(table,new String[]{MyDatabaseHelper.KEY_ID},clause,args,null,null,null);
                if(c==null )
                {

                    return;
                }


                String sel=MyDatabaseHelper.KEY_TRAINEE_ID+"=? and "+MyDatabaseHelper.KEY_ALLOCATED_DATE+"=?";
                String[] sel_args=new String[]{String.valueOf(data[i].item_id),data[i].allocation_date};
                Cursor cur =readDB.query(table,new String[]{MyDatabaseHelper.KEY_ID},sel,sel_args,null,null,null);
                if(cur.getCount()!=0)
                {
                    Toast.makeText(getActivity(),"Duplicate allocation not permitted",Toast.LENGTH_SHORT).show();
                    return;
                }


                ContentValues cv = new ContentValues();
                cv.put(MyDatabaseHelper.KEY_ALLOCATED_DATE,data[i].allocation_date);
                cv.put(MyDatabaseHelper.KEY_COURSE_ID,course_id);
                cv.put(MyDatabaseHelper.KEY_TRAINEE_ID,data[i].item_id);
                cv.put(MyDatabaseHelper.KEY_STATUS,data[i].status);
                cv.put(MyDatabaseHelper.KEY_COMMENTS,data[i].comments);



                if(c.getCount()==0)
                {

                    long result=writeDB.insert(table,null,cv);
                }


                if(c.getCount()!=0)
                {
                    long result=writeDB.update(table, cv, clause, args);
                }

            }

        }
        Toast.makeText(getActivity(),"Saved Successfully",Toast.LENGTH_SHORT).show();
        getActivity().finish();
    }


}
